package com.sf.fy.uav.applet.operate.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sf.fy.uav.applet.login.service.LoginService;
import com.sf.fy.uav.applet.utils.PayUtil;
import com.sf.fy.uav.common.response.operational.CallbackSigningRequest;
import com.sf.fy.uav.common.utils.PhoneEncoderUtil;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.entity.Activity;
import com.sf.fy.uav.entity.InvitationCode;
import com.sf.fy.uav.entity.PromotionStatistics;
import com.sf.fy.uav.mapper.PromotionStatisticsMapper;
import com.sf.fy.uav.rest.*;
import com.sf.fy.uav.user.entity.User;
import com.sf.fy.uav.user.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 01430312
 */
@RestController
@RequestMapping("/home/wx/")
@RequiredArgsConstructor
@Tag(name = "获取微信相关信息", description = "获取微信相关信息")
public class SysWxController {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SysWxController.class);

    private final RestTemplate restTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private PhoneEncoderUtil phoneEncoderUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${proxy-url:sfproxy.intsit.sfcloud.local}")
    private String proxyUrl;


    @Value("${is-use-proxy:false}")
    private boolean isUseProxy;


    @Value("${app.version:1.0.7}")
    private String lastAppVersion;

    @Autowired
    private SigningCallbackInfoRest signingCallbackInfoRest;

    @Autowired
    private InvitationCodeRest invitationCodeRest;

    @Value("${cloud.env_version:develop}")
    private String cloudEnvVersion;

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PromotionStatisticsMapper promotionStatisticsMapper;

    @Autowired
    private PromotionStatisticsRest promotionStatisticsRest;

    @Autowired
    private ActivityRest activityRest;

    @Autowired
    private PlacementPointRest placementPointRest;


    @RequestMapping("/get-wx-qrcode")
    @Parameter(name = "type", description = "0, \"成交奖励")
    @Parameter(name = "userId", description = "用户id")
    @Parameter(name = "page", description = "二维码跳转页面")
    public Rs<String> createQRCode(@RequestParam Integer type, @RequestParam(required = false) String page, @RequestParam String userId, HttpServletResponse response) {
        User user = userMapper.selectById(userId);
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户不存在");
        }
        InvitationCode invitationCode = invitationCodeRest.getByUserId(type, userId);
        if (ObjectUtils.isEmpty(invitationCode)) {
            throw new RuntimeException("邀请码不存在");
        }
        String activityId = invitationCode.getActivityId();
        Activity activity = activityRest.getSettings(activityId);
        if (ObjectUtils.isEmpty(activity)) {
            throw new RuntimeException("活动不存在");
        }
        try {
            //获取AccessToken
            String accessToken = loginService.getStableToken();
            //设置响应类型
            response.setContentType("image/png");
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            //组装参数
            JSONObject jsonObject = new JSONObject();
            //二维码携带参数 不超过32位 参数类型必须是字符串
            jsonObject.put("scene", invitationCode.getId());
            //二维码跳转页面
            jsonObject.put("page", page);
            jsonObject.put("env_version", cloudEnvVersion);

            //二维码的宽度
            jsonObject.put("width", 450);
            //自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
            jsonObject.put("auto_color", false);
            //是否需要透明底色， is_hyaline 为true时，生成透明底色的小程序码
            jsonObject.put("is_hyaline", false);
            //执行post 获取数据流
            byte[] result = doImgPost(url, jsonObject);
            PromotionStatistics promotionStatistics = promotionStatisticsRest.getPromotionStatistics(userId, activityId);
            Date date = new Date();
            if (ObjectUtils.isEmpty(promotionStatistics)) {
                promotionStatistics = new PromotionStatistics();
                promotionStatistics.setCreateTime(date);
                promotionStatistics.setUpdateTime(date);
                promotionStatistics.setUserId(userId);
                promotionStatistics.setActivityId(activityId);
                promotionStatistics.setStartActivityTime(activity.getStartActivityTime());
                promotionStatistics.setPhoneNumber(user.getPhoneNumber());
                promotionStatisticsMapper.insert(promotionStatistics);
            }
            return Rs.success(Base64.getEncoder().encodeToString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Rs.failed();
    }

    /**
     * 获取数据流
     *
     * @param url
     * @param paraMap
     * @return
     */
    public byte[] doImgPost(String url, JSONObject paraMap) {
        byte[] result = null;
        try {

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 设置请求的参数
            JSONObject postData = new JSONObject();
            for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
                postData.put(entry.getKey(), entry.getValue());
            }
            result = com.sf.fy.uav.task.utils.HttpClientUtil.sendPostJsonRepeatProxyForPicture(url, JSONObject.toJSONString(paraMap), proxyUrl, 80, isUseProxy);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return result;
    }

    @PostMapping("/sign-record")
    @Operation(tags = "回调签约记录", description = "回调签约记录")
    public Rs<Void> callbackSigningInfo(@RequestBody Map<String, Object> linkedHashMap) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info(linkedHashMap.toString());
        String bankName = (String) ((Map) linkedHashMap.get("body")).get("bankName");
        String bankNum = (String) ((Map) linkedHashMap.get("body")).get("bankNum");
        Date contractEndTime = null;
        Date contractStartTime = null;
        try {
            contractEndTime = simpleDateFormat.parse((String) ((Map) linkedHashMap.get("body")).get("contractEndTime"));

            contractStartTime = simpleDateFormat.parse((String) ((Map) linkedHashMap.get("body")).get("contractStartTime"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer enterpriseId = (Integer) ((Map) linkedHashMap.get("body")).get("enterpriseId");
        Integer projectId = (Integer) ((Map) linkedHashMap.get("body")).get("projectId");
        String qkId = (String) ((Map) linkedHashMap.get("body")).get("qkId");
        String qkName = (String) ((Map) linkedHashMap.get("body")).get("qkName");
        Integer qkNumb = (Integer) ((Map) linkedHashMap.get("body")).get("qkNumb");
        String qkPhone = (String) ((Map) linkedHashMap.get("body")).get("qkPhone");
        String qkidBackphotoUrl = (String) ((Map) linkedHashMap.get("body")).get("qkidBackphotoUrl");
        String qkidFrontphotoUrl = (String) ((Map) linkedHashMap.get("body")).get("qkidFrontphotoUrl");
        CallbackSigningRequest callbackSigningRequest = new CallbackSigningRequest();
        callbackSigningRequest.setBankName(bankName);
        bankNum = phoneEncoderUtil.encryptString(bankNum);
        callbackSigningRequest.setBankNum(bankNum);
        callbackSigningRequest.setContractEndTime(contractEndTime);
        callbackSigningRequest.setContractStartTime(contractStartTime);
        callbackSigningRequest.setEnterpriseId(enterpriseId);
        callbackSigningRequest.setProjectId(projectId);
        callbackSigningRequest.setQkId(qkId);
        callbackSigningRequest.setQkName(qkName);
        callbackSigningRequest.setQkNumb(qkNumb);
        callbackSigningRequest.setQkPhone(qkPhone);
        callbackSigningRequest.setQkidBackphotoUrl(qkidBackphotoUrl);
        callbackSigningRequest.setQkidFrontphotoUrl(qkidFrontphotoUrl);
        signingCallbackInfoRest.callbackSigningInfo(callbackSigningRequest);
        return Rs.success();
    }

    /**
     * 获取微信js-sdk需要的签名jsapi_ticket
     *
     * @return
     */

//    @RequestMapping("/get-signature")
    @GetMapping("/get-signature")
    @CrossOrigin
    public Rs<Map<String, String>> getSignature() {
        Map<String, String> params = new HashMap<>(10);
        params.put("param1", appid);
        params.put("param2", secret);
        String forObject = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={param1}&secret={param2}", String.class, params);
        JSONObject jsonObject = JSON.parseObject(forObject);
        String accessToken = "";
        if (jsonObject != null) {
            accessToken = (String) jsonObject.get("access_token");
        }
        String jsapiTicket = "";
        if (StringUtils.isNotBlank(accessToken)) {
            Map<String, String> paramsTwo = new HashMap<>(10);
            paramsTwo.put("param1", accessToken);
            String jsapiTicketJson = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={param1}&type=jsapi&offset_type=1'", String.class, paramsTwo);
            JSONObject jsapiTicketObj = JSON.parseObject(jsapiTicketJson);
            if (jsapiTicketObj != null) {
                jsapiTicket = (String) jsapiTicketObj.get("ticket");
            }
        }
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        //这个地址有问题吧，不应该写死成测试的
        String url = "https://ie-uocs-out.sit.sf-express.com:4433/index.html";
        String signatureTwo = genSignatureJSSDK(noncestr, jsapiTicket, timestamp, url);
        Map<String, String> map = new HashMap<>(10);
        map.put("noncestr", noncestr);
        map.put("timestamp", timestamp);
        map.put("signature", signatureTwo);
        return Rs.success(map);
    }

    private String genSignatureJSSDK(String nonce, String jsapiTicket, String timestamp, String url) {
        StringBuffer sb = new StringBuffer();
        sb.append("jsapi_ticket=" + jsapiTicket)
                .append("&noncestr=" + nonce)
                .append("&timestamp=" + timestamp)
                .append("&url=" + url);
        logger.info("genSignatureJSSDK：" + sb);
        return PayUtil.sha1(sb.toString().trim());
    }

    @GetMapping("/generate-scheme")
    @CrossOrigin
    public Rs<String> generateScheme() {
        Map<String, String> params = new HashMap<>(10);
        params.put("param1", appid);
        params.put("param2", secret);
        String forObject = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={param1}&secret={param2}", String.class, params);
        JSONObject jsonObject = JSON.parseObject(forObject);
        String accessToken = "";
        if (jsonObject != null) {
            accessToken = (String) jsonObject.get("access_token");
        }
        String schemeCodeTwo = "";
        if (StringUtils.isNotBlank(accessToken)) {
            Map<String, Map<String, String>> paramsTwo = new HashMap<>(10);
            Map<String, String> paramsOne = new HashMap<>(10);
            paramsOne.put("path", "pages/phone-login/phone-login");
            paramsOne.put("env_version", "develop");
            paramsTwo.put("jump_wxa", paramsOne);
            String schemeCode = restTemplate.postForObject("https://api.weixin.qq.com/wxa/generatescheme?access_token=" + accessToken, paramsTwo, String.class);
            JSONObject schemeCodeObj = JSON.parseObject(schemeCode);
            if (schemeCodeObj != null) {
                schemeCodeTwo = (String) schemeCodeObj.get("openlink");
            }
        }
        return Rs.success(schemeCodeTwo);
    }

    @GetMapping("/generate_urlLink")
    @CrossOrigin
    public Rs<String> generateUrlLink() {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl,80));
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setProxy(proxy);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        Map<String, String> params = new HashMap<>(10);
        params.put("param1", appid);
        params.put("param2", secret);
        String forObject = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={param1}&secret={param2}", String.class, params);
        JSONObject jsonObject = JSON.parseObject(forObject);
        String accessToken = "";
        if (jsonObject != null) {
            accessToken = (String) jsonObject.get("access_token");
        }
        String schemeUrl = "";
        if (StringUtils.isNotBlank(accessToken)) {
            Map<String,String> paramTwo = new HashMap<>(10);
            paramTwo.put("path", "pages/phone-login/phone-login");
            paramTwo.put("env_version", "develop");
            String link = restTemplate.postForObject("https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken, paramTwo, String.class);
            JSONObject linkObj = JSON.parseObject(link);
            if (linkObj != null) {
                schemeUrl = (String) linkObj.get("url_link");
            }
        }
        return Rs.success(schemeUrl);
    }


    @GetMapping("/get-newly-release-status")
    public Rs<Integer> getReleaseStatus(@RequestParam String appVersion) {
        if (appVersion.compareTo(lastAppVersion) < 0) {
            //以前过审的
            return Rs.success(-1);
        } else if (appVersion.compareTo(lastAppVersion) == 0) {
            //最新过审的
            return Rs.success(0);
        } else if (appVersion.compareTo(lastAppVersion) > 0) {
            //未过审的
            return Rs.success(1);
        }
        return Rs.success(null);
    }
}
